import {jwtDecode} from "jwt-decode";
export default () => {
    const useAuthToken = () => useState('auth_token')
    const useAuthUser = () => useState('auth_user')
    const useAuthLoading = () => useState('auth_loading', () => true)

    const setToken = (newToken) => {
        const authToken = useAuthToken()
        authToken.value = newToken
    }

    const setUser = (newUser) => {
        const authUser = useAuthUser()
        authUser.value = newUser
    }

    const setIsAuthLoading = (value) => {
        const authLoading = useAuthLoading()
        authLoading.value = value
    }

    const login = ({ username, password }) => {
        return new Promise(async (resolve, reject) => {
            try {
                const data = await $fetch('/api/auth/login', {
                    method: 'POST',
                    body: {
                        username,
                        password
                    }
                })

                setToken(data.access_token)
                setUser(data.user)

                resolve(true)
            } catch (error) {
                reject(error)
            }
        })
    }
    const refreshToken = ()=>{
       return  new Promise(async (resolve, reject) => {
           try {
               const data = await $fetch('/api/auth/refresh')
               setToken(data.access_token)
               resolve(true)
           } catch (error) {
               reject(error)
           }
        })
    }
    const getUser = ()=>{
        return new Promise(async (resolve, reject) => {
            try {
                const data = await useFetchApi('/api/auth/user')
                setUser(data.user)
                resolve(true)
            } catch (error) {
                reject(error)
            }
        })
    }
    const reRefreshAccessToken = () => {
        // 超时了就刷新
        const authToken = useAuthToken()
        if (!authToken.value)return ;
        const jwt = jwtDecode(authToken.value)
        const newRefreshTime = jwt.exp - 60000
        setTimeout(async () => {
            await refreshToken()
            reRefreshAccessToken()
        }, newRefreshTime);
    }
    const initAuth = ()=>{
        // 每次页面刷新调用 ， 从新刷新数据
        return new Promise(async (resolve, reject) => {
            setIsAuthLoading(true)
            try {
                // 刷新token
                await  refreshToken()
                // 刷新用户信息
                await  getUser()

                reRefreshAccessToken()

                resolve(true)
            }catch (e){
                console.log(e)
                reject(e)
            }finally {
                console.log(11)
                setIsAuthLoading(false)
            }
        })
    }
    const logout = () => {
        return new Promise(async (resolve, reject) => {
            try {
                await useFetchApi('/api/auth/logout', {
                    method: 'POST'
                })
                setToken(null)
                setUser(null)
                navigateTo({
                    path: `/`
                })
                resolve()
            } catch (error) {
                reject(error)
            }
        })
    }
    return {
        login,
        useAuthUser,
        useAuthToken,
        useAuthLoading,
        initAuth,
        logout
    }
}